/** *************
 * ***********请求相关的工具库
 * ***********/

import axios from 'axios'
import { requestInterception } from '../request/interception'
import { removeAllStorage } from '../utils/storage'
const default_headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}
const axiosInstance = axios.create({
    baseURL: process.env.NODE_ENV  === 'development' ? process.env.REACT_APP_DEV_API_URL : process.env.REACT_APP_PRO_API_URL,
    timeout: 5000,
})

export default function request(config = {}){
    if(!config.method) {
        config.method = 'get'
    }
    let requestParams = { params: { ...config.data }}
    if (config.method.toLowerCase() === 'post') {
        requestParams = { data: { ...config.data }}
    }
    axiosInstance.defaults.withCredentials = config?.withCredentials || true
    axiosInstance.defaults.headers["Content-Type"] = config.contentType ||  default_headers["Content-Type"]
    return new Promise((resolve, reject) => {
        if(!config.url) return
        axiosInstance({
            url: config.url,
            method: config.method || 'get',
            ...requestParams,
        }).then(res => {
            if ((res.status = 200 || res.status < 400) && res.status < 500) {
                if(res.headers['content-type'].includes('svg')) {
                    resolve(res.data)
                } else {
                    const { code = 0, msg } = res.data
                    if (code === 1) {
                        resolve(res.data)
                    }
                    else {
                        window.$message.error(msg)
                        reject(msg)
                    }
                }
            }
            else {
                reject(res)
            }
        }).catch(e => {
            if(e.code === "ERR_NETWORK") window.$message.error( '网络连接错误')
            if(e.response) {
                if(e.response.status === 401) {
                    window.$message.error( '登录失效或者未登录,请先登录')
                    removeAllStorage()
                    setTimeout(() => {
                        window.location.href = '/login'
                    }, 2000)
                }
            }
        }).finally(_ => {
        })
    })
}
// 请求拦截
axiosInstance.interceptors.request.use(requestInterception)
